package com.dkm.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.dkm.entity.Counselor;
import com.dkm.entity.Student;
import com.dkm.entity.Users;
import com.dkm.repository.CounselorRepository;
import com.dkm.repository.StudentRepository;
import com.dkm.repository.UsersRepository;
import com.dkm.service.CounselorService;
import com.dkm.service.StudentService;
import com.dkm.util.ResultUtil;

@Service
public class StudentServiceImpl implements StudentService {

	//注入学生持久层
	@Autowired
	private StudentRepository studentRepository;
	//注入用户持久层
	@Autowired
	private UsersRepository usersRepository;
	//注入咨询师持久层
	@Autowired
	private CounselorRepository counselorRepository;
	//注入咨询师业务层
	@Autowired
	private CounselorService counselorService;
	
	@Override
	public Page<Student> findAllStudents(Map<String, Object> map, Pageable pageable) {
		return studentRepository.findAll(this.get(map), pageable);
	}

	private Specification<Student> get(Map<String, Object> map) {
		return new Specification<Student>() {

			@Override
			public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				//1创建Predicate对象，动态sql表达式
				Predicate predicate=criteriaBuilder.conjunction();
				//2创建一个集合存放多个条件，动态sql表达式集合
				List<Expression<Boolean>> expressions=predicate.getExpressions();
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				
				Student student=(Student) map.get("student");
				//学生姓名
				if(!StringUtils.isEmpty(student.getSname())) {
					expressions.add(criteriaBuilder.like(root.get("sname"), "%"+student.getSname()+"%"));
				}
				//电话
				if(!StringUtils.isEmpty(student.getPhone())) {
					expressions.add(criteriaBuilder.like(root.get("phone"), "%"+student.getPhone()+"%"));
				}
				//网络咨询师
				if(!StringUtils.isEmpty(map.get("network_counselor_id"))) {
					expressions.add(criteriaBuilder.equal(root.get("network_counselor").get("counselor_id"), map.get("network_counselor_id")));
				}
				
				//咨询师
				if(!StringUtils.isEmpty(map.get("counselor_id"))) {
					expressions.add(criteriaBuilder.equal(root.get("counselor").get("counselor_id"), map.get("counselor_id")));
				}
				//是否缴费
				if(!StringUtils.isEmpty(student.getIs_payment())) {
					expressions.add(criteriaBuilder.equal(root.get("is_payment"), student.getIs_payment()));
				}
				//是否回访
				if(!StringUtils.isEmpty(student.getIs_return_visit())) {
					expressions.add(criteriaBuilder.equal(root.get("is_return_visit"), student.getIs_return_visit()));
				}
				//QQ
				if(!StringUtils.isEmpty(student.getQq())) {
					expressions.add(criteriaBuilder.like(root.get("qq"), "%"+student.getQq()+"%"));
				}
				
				try {
					//创建时间
					if(!StringUtils.isEmpty(map.get("createBeginDate"))) {
						expressions.add(criteriaBuilder.greaterThanOrEqualTo(root.get("create_time"), sdf.parse(map.get("createBeginDate").toString())));
					}
					if(!StringUtils.isEmpty(map.get("createEndDate"))) {
						expressions.add(criteriaBuilder.lessThanOrEqualTo(root.get("create_time"), sdf.parse(map.get("createEndDate").toString())));
					}
					//上门时间
					if(!StringUtils.isEmpty(map.get("visitBeginDate"))) {
						expressions.add(criteriaBuilder.greaterThanOrEqualTo(root.get("visit_time"), sdf.parse(map.get("visitBeginDate").toString())));
					}
					if(!StringUtils.isEmpty(map.get("visitEndDate"))) {
						expressions.add(criteriaBuilder.lessThanOrEqualTo(root.get("visit_time"), sdf.parse(map.get("visitEndDate").toString())));
					}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				return predicate;
			}
		};
	}

	@Transactional //开启事务
	@Override
	public ResultUtil saveAndFlushStudent(Student student) {
		ResultUtil resultUtil=null;
		String operation="";
		if(student.getSid()!=null) {
			operation="修改";
			//根据id获取学生信息
			Student oldStudent=studentRepository.findById(student.getSid()).get();
			student.setCreate_time(oldStudent.getCreate_time());
			
		}else {
			operation="添加";
			//生成id
			student.setSid(UUID.randomUUID().toString());
			student.setCreate_time(new Date());
		}
		
		Student s= studentRepository.saveAndFlush(student);
		
		if(s!=null) {
			resultUtil=new ResultUtil(0, operation+"成功", s);
		}else {

			resultUtil=new ResultUtil(-1, operation+"失败", null);
		}
		return resultUtil;
	}
	
	@Transactional //开启事务
	@Override
	public ResultUtil deleteStudent(String sid) {

		//根据id获取学生
		Student student=studentRepository.findById(sid).get();
		
		try {
			studentRepository.delete(student);
			return new ResultUtil(0, "删除成功", null);
		} catch (Exception e) {
			return new ResultUtil(-1, "删除失败", null);
		}
		
	}
	@Transactional //开启事务
	@Override
	public ResultUtil addStudent(String user_id, Student student) {
		ResultUtil resultUtil=null;
		//根据用户id获咨询师信息
		Users user=usersRepository.findById(user_id).get();
		Counselor netCounselor=counselorRepository.getNetCounselorByUser_id(user_id);
		if(netCounselor!=null&&"网络咨询师".equals(netCounselor.getRoleName())) {
			//设置录入的用户信息(网络咨询师)
			student.setNetwork_counselor(netCounselor);
			student.setEntering_people_name(netCounselor.getCounselor_name());
			
		}else {
			student.setEntering_people_name(user.getLogin_name());
		}
		
		//生成id
		student.setSid(UUID.randomUUID().toString());
		student.setCreate_time(new Date());
		
		Student s= studentRepository.saveAndFlush(student);
		if(s!=null) {
			resultUtil=new ResultUtil(0, "添加成功", s);
			//如果是网络咨询师
			if(netCounselor!=null&&"网络咨询师".equals(netCounselor.getRoleName())) {
				//判断该网络咨询师是否开启自动分配
				if("是".equals(netCounselor.getIs_allot())) {
					
					//根据网络咨询师id获取未分配的学生
					List<Student> sList=studentRepository.getStudentByNetCounselor_id(netCounselor.getCounselor_id());
					//获取已签到的咨询师
					List<Counselor> counselors=counselorService.getSignCounselor();
					//执行分配
					counselorService.randomAllocation(sList, counselors);
				}
			}
		}else {

			resultUtil=new ResultUtil(-1, "添加失败", null);
		}
		return resultUtil;
	}
	@Transactional //开启事务
	@Override
	public ResultUtil updateStudent(Student student) {
		ResultUtil resultUtil=null;
		//根据id获取学生信息
		Student oldStudent=studentRepository.findById(student.getSid()).get();
		student.setCreate_time(oldStudent.getCreate_time());
		student.setEntering_people_name(oldStudent.getEntering_people_name());
		
		//网络咨询师信息
		if(oldStudent.getNetwork_counselor()!=null) {
			student.setNetwork_counselor(oldStudent.getNetwork_counselor());
		}
		
		//咨询师信息
		if(oldStudent.getCounselor()!=null) {
			student.setCounselor(oldStudent.getCounselor());
		}
		
		Student s= studentRepository.saveAndFlush(student);
		if(s!=null) {
			resultUtil=new ResultUtil(0, "修改成功", s);
		}else {

			resultUtil=new ResultUtil(-1, "修改失败", null);
		}
		return resultUtil;
	}

	@Override
	public List<Student> batchFindBySid(String sids) {
		if(sids!="") {
			String[] idArr=sids.split(",");
			//转换为list集合
			List<String> sidList=new ArrayList<String>(Arrays.asList(idArr));
			
			//根据传参id批量获取学生信息
			return studentRepository.findAllById(sidList);
		}
		//为空获取全部学生信息
		return studentRepository.findAll();
	}
	
	@Transactional //开启事务
	@Override
	public List<Student> batchAddStudent(List<Student> sList) {
		
		for (Student student : sList) {
			student.setSid(UUID.randomUUID().toString());
			if(student.getCreate_time()==null) {
				student.setCreate_time(new Date());
			}
		}
		//批量保存
		return studentRepository.saveAll(sList);
	}

}
